makeSearchCommand({
//to subscribe to the command ,go to: <http://gist.github.com/13700>
//project: <http://code.google.com/p/tl-ubiquity-commands/>
  author: {name: "Thomas Lemberger", email: "thomas.lemberger@gmail.com"},
  license: "GPL",
  name: "pubmed",
  help: "Search selected terms or directly typed in the input line. The number of records to be displayed can be specified by adding '#number' somewhere in the query (eg. #3 will show only 3 records, default is 5, maximum is 15).",
  url: "http://www.ncbi.nlm.nih.gov/pubmed?term={QUERY}",
  icon: "http://www.ncbi.nlm.nih.gov/favicon.ico",
  description: "Searches <a href='http://www.ncbi.nlm.nih.gov/pubmed'>PubMed</a>.",
  preview: function(previewBlock, directObject){

    const PUBMED_MAX_RECORDS=15;
    const PUBMED_DEFAULT_RECORDS=5;
    const PUBMED_MAX_AUTHORS=20 ;

    var selectedText=CmdUtils.getSelection();
    var inputText = directObject.text;
    var searchTerm;
    var recordsToDisplay = PUBMED_DEFAULT_RECORDS=5;
    var matches = inputText.match(/#(\d+)/);    
    if (matches){
       recordsToDisplay=Math.min(matches[1],PUBMED_MAX_RECORDS);  
    };
    if (selectedText && inputText.match(/^\s*#\d+$/)){//command line only to modify number of records
      searchTerm = selectedText;
    } else {
      searchTerm = inputText;
      searchTerm = inputText.replace(/#\d+/,'');
    };
    var pTemplate = "Searches PubMed for the following terms: \"<b>${query}</b>\" (limit to ${number} records)";
    var pData = {query: searchTerm, number: recordsToDisplay};
    previewBlock.innerHTML = CmdUtils.renderTemplate(pTemplate, pData);
   
    var url1="http://eutils.ncbi.nlm.nih.gov/entrez/eutils/esearch.fcgi";
    var params1 = {
      db: "pubmed",
      usehistory: "y",
      term: searchTerm,
      sort: "pub date",
      retmode: "xml"
    };
    
    jQuery.ajax({
      type: "GET",
      url: url1,
      data: params1,
      dataType: "text",
      //I would have liked to use dataType: "xml" but jQuery returned error because...
      //Entrez' e-utilities send their response with "Content-Type: text/html" header
      
      error: function(response){previewBlock.innerHTML = "Error searching pubmed: "+ response;},

      success: function (response){
        var parser = new window.DOMParser();
        xml = parser.parseFromString(response,"text/xml");
        data=jQuery(xml);
        var count=data.find("Count:first").text();
        //var queryKey=data.find("QueryKey").text();
        //var webEnv=jQuery(data).find("WebEnv").text();
        //did not always work, so I prefer to use list of retrieved pmids
        var list=[];
        jQuery("eSearchResult IdList Id",data).each(function(){
          list.push(jQuery(this).text())
        });
        var pmids=list.join(",");

        url2="http://eutils.ncbi.nlm.nih.gov/entrez/eutils/esummary.fcgi";
 
        params2={
          db: "pubmed",
          id: pmids,
          //WebEnv: webEnv,
          //query_key: queryKey,
          //ncbi's default is retmax=20
          retmax: recordsToDisplay,
          retmode: "xml"
        };
        
        jQuery.ajax({
           type: "GET",
           url: url2,
           data: params2,
           dataType: "text",
           //same as above
           
           error: function(response2){previewBlock.innerHTML = "Error retrieving summaries: "+ response2;},
           
           success: function(response2){
              previewBlock.innerHTML ="parsing results...";
              xml2 = parser.parseFromString(response2,"text/xml");
              data2=jQuery(xml2);
              var summaryData=[];
              var errorCheck=data2.find("ERROR");
              if (errorCheck.text()){
                previewBlock.innerHTML="no results"}
              else {
                data2.find("DocSum").slice(0, recordsToDisplay).each(function(itemIndex) {
                  previewBlock.innerHTML ="parsing result "+itemIndex;
                  var summary = jQuery(this);
          
                  var newSummary={
                     ti: summary.find("Item[Name='Title'][Type='String']").text(), 
                     id: summary.find("Id").text(),
                     lastau: summary.find("Item[Name='LastAuthor']").text(),
                     yr: summary.find("Item[Name='PubDate']").text().match(/^\d{2,4}/),
                     vol: summary.find("Item[Name='Volume']").text(),
                     issue: summary.find("Item[Name='Issue']").text(),
                     pp: summary.find("Item[Name='Pages']").text(),
                     so: summary.find("Item[Name='Source']").text(),
                     ti: summary.find("Item[Name='Title']").text(),
                  };

                  var authorList=[];

                  var authors=summary.find("Item[Name='AuthorList']");
                  authors=jQuery(authors);
                  authors.find("Item[Name='Author']").slice(0, PUBMED_MAX_AUTHORS).each(function(authorIndex) {
                    var auName=jQuery(this).text();
                    authorList.push({name: auName});
                  });

                  //remove last author of the list of authors; last author already stored in newSummary.lastau
                  authorList.pop();
                  newSummary.aulist=authorList;
                  if (authorList[0]){newSummary.firstau=authorList[0].name} else {newSummary.firstau=""};
                
                  var fullRef="";
                  for (var i in authorList) {
                    if (i<(authorList.length-1)) {fullRef+=authorList[i].name+", "} 
                    else {fullRef+=authorList[i].name+" and "};
                  };
                  fullRef+=newSummary.lastau+" ("+newSummary.yr+"). "+newSummary.ti+" "+newSummary.so+" "+newSummary.vol+":"+newSummary.pp+".";
                  newSummary.fullref=escape(fullRef);//will need to remember unescaping it...
                  summaryData.push(newSummary);  
                          
                });

                var style="<style type='text/css'>"+
                  ".pubmed-search {font: 12px Arial, Verdana, Sansserif; color:black; background-color:white} "+
                  "li {padding: 8px 0px}"+
                  ".pubmed-link:hover {cursor: pointer} "+
                  ".pubmed-link:hover,a:hover{text-decoration:underline} "+
                  ".authorlist {color:blue} "+
                  "</style>";

                var html=
                  "<p>"+recordsToDisplay+"/"+count+" results for \""+searchTerm.substring(0,15)+"...\":</p>"+
                  "<ol class='pubmed-search'>";
                for (i in summaryData){
                  var item=summaryData[i];
                  html+=
                  "    <li>"+
                  "      <a href='http://www.ncbi.nlm.nih.gov/pubmed/"+item.id+"'>"+item.ti+"</a>"+
                  "      <div class='authorlist' style='font-size:small;padding:4px 0px 0px 0px'>";
                  for (j in item.aulist){
                     var author=item.aulist[j];
                     html+="<a href='http://www.ncbi.nlm.nih.gov/pubmed?term="+author.name+"[au]'>"+
                          author.name+"</a>, ";
                  };
                  html+="<a href='http://www.ncbi.nlm.nih.gov/pubmed?term="+item.lastau+"[au]'>"+
                          item.lastau+"</a><br/>"+
                  "      </div>"+
                  "       <div style='font-size:small;padding:0px 0px 3px 0px'><i>"+item.so+"</i> "+item.yr+
                  "      </div>"+
                  "      <div style='font-size:small'>"+
                  "         Insert: "+
                  "         <span class='pubmed-link' onclick=\"setSelection('"+item.firstau+" et <i>al</i>, "+
                            item.yr+"',{text: '"+item.firstau+" et <i>al</i>, "+item.yr+"'})\">citation</span> | "+
                  "         <span class='pubmed-link' onclick=\"setSelection(unescape('"+
                    escape("<a href='http://www.ncbi.nlm.nih.gov/pubmed/"+item.id+"'>" + item.firstau + " et <i>al</i>, " + item.yr + "</a>")+
                 "'),"+
                 "{text: unescape('"+
                    escape("<a href='http://www.ncbi.nlm.nih.gov/pubmed/"+item.id+"'>" + item.firstau + " et <i>al</i>, " + item.yr + "</a>")+
                  "')})\">"+
                  "link\+citation</span> | "+
                  "         <span class=\"link\" onclick=\"javascript:setSelection(unescape('"+item.fullref+"'),{text: unescape('"+item.fullref+"')})\">"+
                  "full reference</span>"+
                  "      </div>"+
                  "    </li>";
                };
                html+="</ol>";
                
                previewBlock.ownerDocument.setSelection = function(content,option){CmdUtils.setSelection(content,option)};

                previewBlock.innerHTML = style + html;
              }
           }
        });      
      }
    });
  }
});
